package com.wu.foodsafetyplayer.app;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dueeeke.videoplayer.exo.ExoMediaPlayerFactory;
import com.dueeeke.videoplayer.ijk.IjkPlayerFactory;
import com.dueeeke.videoplayer.player.AndroidMediaPlayerFactory;
import com.dueeeke.videoplayer.player.VideoView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.wu.foodsafetyplayer.R;
import com.wu.foodsafetyplayer.app.adapter.AppVideoAdapter;
import com.wu.foodsafetyplayer.app.adapter.MonitorVideoAdapter;
import com.wu.foodsafetyplayer.app.bean.AppVideoBackBean;
import com.wu.foodsafetyplayer.app.bean.MonitorVideoBean;
import com.wu.foodsafetyplayer.app.dialog.LoadingUtil;
import com.wu.foodsafetyplayer.http.CommonOkHttpClient;
import com.wu.foodsafetyplayer.utils.ACache;
import com.wu.foodsafetyplayer.utils.AnimationUtil;
import com.wu.foodsafetyplayer.utils.datepicker.CustomDatePicker;
import com.wu.foodsafetyplayer.utils.datepicker.DateFormatUtils;
import com.wu.foodsafetyplayer.utils.tv.TimeUtils;

import java.io.IOException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AppVideoActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, VideoView.OnStateChangeListener {
    private static final String TAG = AppVideoActivity.class.getSimpleName();
    private Context context;
    private TextView titleTv;
    private ImageView backImg, sosoImg;
    private VideoView videoView;
    private ImageView videoImg;
    private GridView videoGridView;
    private TextView liveTV, backTV, backTVPlayer, startTime, stopTime;

    private AppVideoBackBean appVideoBackBean;
    private String resStr;
    private String url_hls, deviceid, channel;//视频预览实时流、设备id、通道id

    private CustomDatePicker mStartPicker, mStopPicker;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_activity_video);
        context = this;
        initView();
        initStartPicker();
        initStopPicker();
        //player("http://daxun.tpddns.cn:81/live/ch26_1_1.m3u8");
    }

    public void initView() {
        titleTv = findViewById(R.id.app_video_title);
        backImg = findViewById(R.id.app_video_back);
        backImg.setOnClickListener(this);

        videoView = findViewById(R.id.app_video);
        videoView.setFocusable(false);
        videoView.setFocusableInTouchMode(false);
        videoView.setScreenScaleType(1);
        videoView.addOnStateChangeListener(this);
        //使用IjkPlayer解码
        //videoView.setPlayerFactory(IjkPlayerFactory.create());
        //使用ExoPlayer解码
        videoView.setPlayerFactory(ExoMediaPlayerFactory.create());
        //使用MediaPlayer解码
        //videoView.setPlayerFactory(AndroidMediaPlayerFactory.create());

        videoImg = findViewById(R.id.app_video_img);

        videoGridView = findViewById(R.id.app_video_gv);
        videoGridView.setOnItemClickListener(this);
        resStr = ACache.get(context).getAsString("vod_data");
        Log.e(TAG, "initView resStr: " + resStr);
        if (!TextUtils.isEmpty(resStr)) {
            try {
                appVideoBackBean = new Gson().fromJson(resStr, AppVideoBackBean.class);
                if (appVideoBackBean != null && appVideoBackBean.data != null && !appVideoBackBean.data.isEmpty()) {
                    handler.sendEmptyMessage(0);
                }
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(1);
            }
        }

        liveTV = findViewById(R.id.app_video_live);
        backTV = findViewById(R.id.app_video_back_player);
        liveTV.setOnClickListener(this);
        backTV.setOnClickListener(this);
        backTVPlayer = findViewById(R.id.app_video_back_soso);
        backTVPlayer.setOnClickListener(this);
        sosoImg = findViewById(R.id.app_video_back_soso_img);
        sosoImg.setOnClickListener(this);
        startTime = findViewById(R.id.app_video_back_start);
        stopTime = findViewById(R.id.app_video_back_stop);
        startTime.setOnClickListener(this);
        stopTime.setOnClickListener(this);
    }

    public void initData(String deviceid, String channel, String mode, String start, String stop) {
        CommonOkHttpClient.FUNC_TASK.execute(new Runnable() {
            @Override
            public void run() {
                String url = "http://daxun.tpddns.cn:81/QueryRecord?deviceid=" + deviceid + "&channel=" + channel + "&mode=" + mode + "&start=" + start + "&stop=" + stop;
                Log.e(TAG, "initData url: " + url);
                OkHttpClient client = new OkHttpClient().newBuilder().build();
                Request request = new Request.Builder()
                        .url(url)
                        .method("GET", null)
                        .addHeader("content-type", "form-data")
                        .addHeader("Cookie", "IDHTTPSESSIONID=r4EN2qalGkkbZUS")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String res = response.body().string();
                    Log.e(TAG, "run res: " + res);
                    if (!TextUtils.isEmpty(res)) {
                        ACache.get(context).put("vod_data", res);
                        appVideoBackBean = new Gson().fromJson(res, AppVideoBackBean.class);
                        if (appVideoBackBean != null && appVideoBackBean.data != null && !appVideoBackBean.data.isEmpty()) {
                            Log.e(TAG, "run: 解析成功");
                            if (!res.equals(resStr)) {
                                handler.sendEmptyMessage(0);
                            }
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                AppVideoAdapter appVideoAdapter = new AppVideoAdapter(context, appVideoBackBean);
                videoGridView.setAdapter(appVideoAdapter);
            } else if (msg.what == 1) {
                AppVideoAdapter appVideoAdapter = new AppVideoAdapter(context, null);
                videoGridView.setAdapter(appVideoAdapter);
            }
        }
    };

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        videoView.resume();
        Intent intent = getIntent();
        if (intent.hasExtra("url")) {
            url_hls = intent.getStringExtra("url");
            player(url_hls);
            //处理录像回放请求接口参数
            String[] urls = url_hls.split("[/]");
            String w = urls[urls.length - 1];
            if (!TextUtils.isEmpty(w)) {
                String[] ws = w.split("[_]");
                if (ws.length > 2) {
                    deviceid = ws[0].substring(2, ws[0].length());
                    channel = ws[1];
                    Log.e(TAG, "onResume ws[0]:" + deviceid);
                    Log.e(TAG, "onResume ws[1]:" + channel);
                    String stop = TimeUtils.getTime(TimeUtils.getCurrentTimeInLong() - (1000 * 60 * 60), TimeUtils.STRING_DATE_FORMAT_DATE);
                    Log.e(TAG, "onResume  stop:" + stop);
                    String start = TimeUtils.getTime(TimeUtils.getCurrentTimeInLong() - (1000 * 60 * 60 * 24), TimeUtils.STRING_DATE_FORMAT_DATE);
                    Log.e(TAG, "onResume  start:" + start);
                    initData(deviceid, channel, "1", start, stop);
                }
            }
        }
        if (intent.hasExtra("name")) {
            titleTv.setText(intent.getStringExtra("name"));
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_video_back:
                videoView.release();
                AppVideoActivity.this.finish();
                break;
            case R.id.app_video_live:
                AnimationUtil.setScaleAnimation(this, liveTV);
                player(url_hls);
                break;
            case R.id.app_video_back_player:
                AnimationUtil.setScaleAnimation(this, backTV);
                playerByBack(0);
                break;
            case R.id.app_video_back_soso:
                AnimationUtil.setScaleAnimation(this, backTVPlayer);
                initData(deviceid, channel, "1", startTime.getText().toString() + "00", stopTime.getText().toString() + "00");
                break;
            case R.id.app_video_back_soso_img:
                initData(deviceid, channel, "1", startTime.getText().toString() + "00", stopTime.getText().toString() + "00");
                break;
            //开始时间
            case R.id.app_video_back_start:
                mStartPicker.show(startTime.getText().toString());
                break;
            //结束时间
            case R.id.app_video_back_stop:
                mStopPicker.show(stopTime.getText().toString());
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        playerByBack(i);
    }

    /**
     * 播放回放视频
     *
     * @param i
     */
    public void playerByBack(int i) {
        if (appVideoBackBean == null || appVideoBackBean.data == null || appVideoBackBean.data.isEmpty()) {
            Toast.makeText(context, "当前摄像头没有录制视频", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] starts = appVideoBackBean.data.get(i).start.split("[-]");
        String[] stops = appVideoBackBean.data.get(i).stop.split("[-]");
        if (starts.length != 2 || stops.length != 2) {
            Toast.makeText(context, "开始时间或结束时间有误", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = "http://daxun.tpddns.cn:81/vod/ch" + appVideoBackBean.data.get(i).deviceid + "_" + channel + "_" + starts[0] + starts[1] + "_" + stops[0] + stops[1] + "_0.m3u8";
        Log.e(TAG, "onItemClick  url: " + url);
        player(url);
    }

    /**
     * 播放
     *
     * @param url
     */
    public void player(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        LoadingUtil.INSTANCE.showLoading(AppVideoActivity.this,"加载中");
        videoView.release();
        videoView.setUrl(url);
        videoView.start();
    }


    /**
     * 初始化时间选择器
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initStartPicker() {
        String beginTime = DateFormatUtils.long2Str(System.currentTimeMillis() - (1000 * 60 * 60 * 24), true);
        startTime.setText(beginTime);
        // 结束时间加100年
        final int y = Calendar.getInstance().get(Calendar.YEAR);
        String endTime = (y + 100) + "0101_000000";

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mStartPicker = new CustomDatePicker(this,
                new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        startTime.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mStartPicker.setCancelable(true);
        // 选择时间选择器样式
        mStartPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mStartPicker.setScrollLoop(true);
        // 允许滚动动画
        mStartPicker.setCanShowAnim(true);
    }

    /**
     * 初始化时间选择器
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initStopPicker() {
        String beginTime = DateFormatUtils.long2Str(System.currentTimeMillis() - (1000 * 60 * 60), true);
        stopTime.setText(beginTime);
        // 结束时间加100年
        final int y = Calendar.getInstance().get(Calendar.YEAR);
        String endTime = (y + 100) + "0101_000000";

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mStopPicker = new CustomDatePicker(this,
                new CustomDatePicker.Callback() {
                    @Override
                    public void onTimeSelected(long timestamp) {
                        stopTime.setText(DateFormatUtils.long2Str(timestamp, true));
                    }
                }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mStopPicker.setCancelable(true);
        // 选择时间选择器样式
        mStopPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mStopPicker.setScrollLoop(true);
        // 允许滚动动画
        mStopPicker.setCanShowAnim(true);
    }

    @Override
    public void onPlayerStateChanged(int playerState) {

    }

    @Override
    public void onPlayStateChanged(int playState) {
        Log.i(TAG, "onPlayStateChanged播放状态：" + playState);
        switch (playState) {
            //播放错误
            case VideoView.STATE_ERROR:
                Log.i(TAG, "播放错误");
                LoadingUtil.INSTANCE.dismissLoading(AppVideoActivity.this);
                break;
            //播放中
            case VideoView.STATE_PLAYING:
                LoadingUtil.INSTANCE.dismissLoading(AppVideoActivity.this);
                break;
        }
    }
}
